import { requestObjectInterface, RequestObject, Response } from "../Typescript/app"

export function GET(url: string, data: any, mask?: boolean, maskTitle?: string) {
  return request('GET', url, data, mask, maskTitle)
}

export function POST(url: string, data: any, mask?: boolean, maskTitle?: string) {
  return request('POST', url, data, mask, maskTitle)
}

function request(method:| 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT', url: string, data: any, mask?: boolean, maskTitle?: string | undefined) {
  let requestConfig:requestObjectInterface = new RequestObject()
  let app = getApp();
  requestConfig.domain = app.globalData.environment ?  app.globalData.environment.api_domain : ""
  requestConfig.authorization = app.globalData.environment ? "Bearer " + app.globalData.environment.token : ""
  requestConfig.data = data
  return new Promise((resolve, reject) => {
        wx.showLoading({
            mask: mask ? mask : true,
            title: maskTitle ? maskTitle : "加载中",
        })
        wx.request({
            url: requestConfig.domain + url,
            method: method,
            header: {
                Authorization: requestConfig.authorization
            },
            data: requestConfig.data,
            dataType: 'json',
            success: function(response: Response)
            {
                setTimeout(() => {
                    wx.hideLoading()
                    if(response.data.code == 200)
                    {
                        resolve(response.data.data)
                    }else if(response.data.code == 401) 
                    {
                        wx.reLaunch({ url: "/pages/login/auth/index" })
                    }else if(response.data.message)
                    {
                        reject(response.data.message)
                    }else
                    {
                        reject("网络错误")
                    }
                }, 200)
            },
            fail: function(e)
            {
                setTimeout(() => {
                    wx.hideLoading()
                    reject(e.errMsg ? e.errMsg : "网络错误")
                }, 200)
            }
        })
  })
}

export default {
  GET,
  POST
}